package com.lap.auth.application.role;

import com.lap.auth.domain.role.repository.RoleMenuRepository;
import com.lap.auth.domain.role.service.RoleValidator;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class RoleMenuAppService {

  private final RoleValidator roleValidator;
  private final RoleMenuRepository roleMenuRepository;

  @Transactional(rollbackFor = Exception.class)
  public void replaceMenus(Integer roleId, Set<Integer> menuSet) {
    roleValidator.assertRoleExists(roleId);

    roleMenuRepository.deleteByRoleId(roleId);
    if (CollectionUtils.isNotEmpty(menuSet)) {
      roleMenuRepository.saveAll(roleId, menuSet);
    }
  }

  public List<Integer> getRoleMenusByRoleId(Integer roleId) {
    roleValidator.assertRoleExists(roleId);
    return roleMenuRepository.findByRoleId(roleId);
  }
}
